#include <iostream>
#include <muduo/net/TcpServer.h>
#include <muduo/net/EventLoop.h>
#include <functional>
#include <memory>

using namespace std;
using namespace placeholders;
using namespace muduo;
using namespace muduo::net;

class ChatServer
{
public:
    ChatServer(EventLoop *loop,
               const InetAddress &listenAddr,
               const string &nameArg)
        : _server(loop, listenAddr, nameArg), _loop(loop)
    {
        // 注册用户连接的创建和回调函数
        _server.setConnectionCallback(bind(&ChatServer::onConnection, this, _1));

        // 注册用户读写事件回调函数
        _server.setMessageCallback(bind(&ChatServer::onMessage, this, _1, _2, _3));

        // 设置服务器端的线程数量
        _server.setThreadNum(2);
    }

    void start()
    {
        _server.start();
    }

private:
    // 处理用户连接创建和断开
    void onConnection(const TcpConnectionPtr &conn)
    {
        if(conn->connected())
            cout << conn->peerAddress().toIpPort() << " -> " << conn->localAddress().toIpPort() << " state: on" << endl;
        else
            cout << conn->peerAddress().toIpPort() << " -> " << conn->localAddress().toIpPort() << " state: off" << endl;
    }

    // 处理用户读写世界
    void onMessage(const TcpConnectionPtr &conn, /*连接*/
                   Buffer *buf, /*缓冲区*/
                   Timestamp time /*收到数据的时间信息*/)
    {
        string buffer = buf->retrieveAllAsString();
        cout << time.toString() << "--- recv data: " << buffer << endl;
        conn->send(buffer);
    }

private:
    TcpServer _server;
    EventLoop *_loop;
};

int main()
{
    InetAddress IAddr("0.0.0.0", 8080);
    EventLoop loop;
    std::unique_ptr<ChatServer> svr(new ChatServer(&loop, IAddr, "ChatServer"));
    svr->start();
    loop.loop();
    return 0;
}